﻿using Dapper;
using Dapper.Abstractions;
using Dapper.Bulk;

namespace DataAccess.Api.Endpoints.Blog;

public class Delete : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        // 批量删除示例
        app.MapPost("/api/blogs/bulk-delete", async (IDbConnectionFactory dbConnectionFactory) =>
        {
            using var connection = await dbConnectionFactory.CreateConnectionAsync();

            // 获取ID为偶数的博客以删除
            const string selectSql = "SELECT * FROM blogs WHERE id % 2 = 0 LIMIT 500";
            var blogsToDelete = (await connection.QueryAsync<Models.Blog>(selectSql)).ToList();

            if (!blogsToDelete.Any())
            {
                return Results.NotFound("No blogs found to delete");
            }

            // 配置实体映射
            BulkManager.Entity<Models.Blog>()
                .Table("blogs")
                .Identity(x => x.Id)
                .UseBulkOptions(options =>
                {
	                options.BatchSize = 1000;
                });

            await connection.BulkDeleteAsync(blogsToDelete);
            return Results.Ok($"Successfully bulk deleted {blogsToDelete.Count} blogs");
        })
        .WithName("DeleteBlogs")
        .WithTags(Tags.Blog);
    }
}
